#include "ws.hpp"

my_endpoint::my_endpoint()
{
	// Set logging to be pretty verbose (everything except message payloads)
	c.set_access_channels(websocketpp::log::alevel::all);
	c.clear_access_channels(websocketpp::log::alevel::frame_payload);
	c.set_error_channels(websocketpp::log::elevel::all);

	// Initialize ASIO
	c.init_asio();

	c.start_perpetual();

}
my_endpoint::~my_endpoint()
{

}

int my_endpoint::socket_connect(std::string uri)
{
	websocketpp::lib::error_code ec;
	client::connection_ptr con = c.get_connection(uri, ec);
	if (ec) {
		std::cout << "could not create connection because: " << ec.message() << std::endl;
		return 0;
	}
	con->set_message_handler(websocketpp::lib::bind(
		&my_connection::on_message, 
		connection, 
		websocketpp::lib::placeholders::_1));
	//con->set_open_handler(&on_open);
	// my_connection a;
	con->set_open_handler(websocketpp::lib::bind(
		&my_connection::on_open, 
		connection, 
		websocketpp::lib::placeholders::_1));
	//con->set_fail_handler(&on_fail);
	//con->set_close_handler(&on_close);
	c.connect(con);
	return 0;
}

int my_endpoint::socket_send(websocketpp::connection_hdl hdl,const text_t& text)
{
	uint8_t * temp;
	temp = new uint8_t[1472];
	make_data(text, temp);
	websocketpp::lib::error_code ec;
	std::cout << "send..." << std::endl;
	c.send(hdl, temp, sizeof(temp), websocketpp::frame::opcode::text, ec);
	if (ec) {
		std::cout << "> Error sending message: " << ec.message() << std::endl;
		return -1;
	}
	delete temp;
	return 0;
}

void my_connection::on_message(websocketpp::connection_hdl hdl, client::message_ptr msg) {
	text_t text;
	uint8_t* data = new uint8_t[msg->get_payload().size() + 1];
	memcpy(data, msg->get_payload().c_str(), msg->get_payload().size());
	get_text(text, data);
	action_judgment(hdl,text);
	delete data;
}
void my_connection::on_open(websocketpp::connection_hdl hdl)
{
	std::cout<<"open"<<std::endl;
}
void my_connection::on_close(websocketpp::connection_hdl hdl)
{
	
}
void my_connection::on_fail(websocketpp::connection_hdl hdl)
{

}